package nguyen.hoan.sharelocation;

import java.util.ArrayList;
import java.util.List;

import org.w3c.dom.Document;

import nguyen.hoan.sharelocation.adapter.NavDrawerListAdapter;
import nguyen.hoan.sharelocation.model.FriendSearchModel;
import nguyen.hoan.sharelocation.model.GMapV2Direction;
import nguyen.hoan.sharelocation.model.NavDrawerGroup;
import nguyen.hoan.sharelocation.model.NavDrawerItem;
import nguyen.hoan.sharelocation.service.MyGoogleMapService;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnShowListener;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.PolylineOptions;

public class MainActivity extends Activity {

	private static final int RESULT_SETTINGS = 1;
	private final Context context = this;

	private static int currentMapType = GoogleMap.MAP_TYPE_NORMAL;

	private DrawerLayout mDrawerLayout;
	private ExpandableListView mDrawerListView;
	private ActionBarDrawerToggle mDrawerToggle;
	private Dialog dialog;
	private FriendSearchModel friendSearchModel = new FriendSearchModel();

	// nav drawer title
	private CharSequence mDrawerTitle;

	// used to store app title
	private CharSequence mTitle;

	// slide menu items
	private TypedArray navMenuIcons;
	private String[] mapTypes;

	private ArrayList<NavDrawerItem> navDrawerItems1;
	private ArrayList<NavDrawerItem> navDrawerItems2;
	private List<NavDrawerGroup> navDrawerGroups = new ArrayList<NavDrawerGroup>();
	private NavDrawerListAdapter adapter;

	// Google Map
	private GoogleMap googleMap;

	// MyGoogleMapService
	private MyGoogleMapService myGoogleMapService;

	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		initilizeMap();

		myGoogleMapService = new MyGoogleMapService(this, googleMap);
		myGoogleMapService.settingMapUI();
		myGoogleMapService.bindLocationChangedListener();
		myGoogleMapService.bindMapActionListener();

		mTitle = mDrawerTitle = getTitle();

		// load slide menu items
		mapTypes = getResources().getStringArray(R.array.map_types);

		// nav drawer icons from resources
		navMenuIcons = getResources().obtainTypedArray(R.array.nav_drawer_icons);

		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		mDrawerListView = (ExpandableListView) findViewById(R.id.list_slidermenu);

		// adding nav drawer items to array
		int navDrawerItemBgColor = getResources().getColor(R.color.list_background);
		navDrawerItems1 = new ArrayList<NavDrawerItem>();
		navDrawerItems1.add(new NavDrawerItem(Constant.DRAWER_MAP_TYPES_ROADMAP, mapTypes[0], navMenuIcons.getResourceId(0, -1), navDrawerItemBgColor));
		navDrawerItems1.add(new NavDrawerItem(Constant.DRAWER_MAP_TYPES_SATELLITE, mapTypes[1], navMenuIcons.getResourceId(1, -1), navDrawerItemBgColor));
		navDrawerItems1.add(new NavDrawerItem(Constant.DRAWER_MAP_TYPES_HYBRID, mapTypes[2], navMenuIcons.getResourceId(2, -1), navDrawerItemBgColor));

		navDrawerItems2 = new ArrayList<NavDrawerItem>();
//		navDrawerItems2.add(new NavDrawerItem(Constant.ENTER_FRIEND_LOCATION, "Enter your friend location", navMenuIcons.getResourceId(5, -1),
//				navDrawerItemBgColor));

		navDrawerGroups.add(new NavDrawerGroup(getResources().getString(R.string.map_types), navMenuIcons.getResourceId(3, -1), getResources().getColor(
				R.color.list_background), navDrawerItems1));
		/*navDrawerGroups.add(new NavDrawerGroup(getResources().getString(R.string.friend_location), navMenuIcons.getResourceId(4, -1), getResources().getColor(
				R.color.list_background), navDrawerItems2));*/

		// Recycle the typed array
		navMenuIcons.recycle();

		mDrawerListView.setOnChildClickListener(new SlideMenuClickListener());

		// setting the nav drawer list adapter
		adapter = new NavDrawerListAdapter(this, navDrawerGroups);
		mDrawerListView.setAdapter(adapter);

		// enabling action bar app icon and behaving it as toggle button
		getActionBar().setDisplayHomeAsUpEnabled(true);
		getActionBar().setHomeButtonEnabled(true);

		mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer, // nav
																								// menu
																								// toggle
																								// icon
				R.string.app_name, // nav drawer open - description for
									// accessibility
				R.string.app_name // nav drawer close - description for
									// accessibility
		) {
			public void onDrawerClosed(View view) {
				getActionBar().setTitle(mTitle);
				// calling onPrepareOptionsMenu() to show action bar icons
				invalidateOptionsMenu();
			}

			public void onDrawerOpened(View drawerView) {
				getActionBar().setTitle(mDrawerTitle);
				// calling onPrepareOptionsMenu() to hide action bar icons
				invalidateOptionsMenu();
			}
		};
		mDrawerLayout.setDrawerListener(mDrawerToggle);
	}

	/**
	 * function to load map. If map is not created it will create it for you
	 * */
	private void initilizeMap() {
		if (googleMap == null) {
			googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();

			// check if map is created successfully or not
			if (googleMap == null) {
				Toast.makeText(getApplicationContext(), "Sorry! unable to create maps", Toast.LENGTH_SHORT).show();
			}
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		initilizeMap();
		redrawMap();
	}

	private void redrawMap() {
		myGoogleMapService.changeMapType(currentMapType);
		if(friendSearchModel.getLatitude().equals("1")){
			LatLng fromPosition = new LatLng(13.687140112679154, 100.53525868803263);
			LatLng toPosition = new LatLng(13.683660045847258, 100.53900808095932);

			GMapV2Direction md = new GMapV2Direction();

			Document doc = md.getDocument(fromPosition, toPosition, GMapV2Direction.MODE_DRIVING);
			ArrayList<LatLng> directionPoint = md.getDirection(doc);
			PolylineOptions rectLine = new PolylineOptions().width(3).color(Color.RED);

			for (int i = 0; i < directionPoint.size(); i++) {
				rectLine.add(directionPoint.get(i));
			}

			googleMap.addPolyline(rectLine);
		}
	}

	/**
	 * Slide menu item click listener
	 * */
	private class SlideMenuClickListener implements ExpandableListView.OnChildClickListener {

		@Override
		public boolean onChildClick(ExpandableListView parent, View view, int groupPosition, int childPosition, long paramLong) {

			NavDrawerItem tag = (NavDrawerItem) view.getTag();
			switch (tag.getId()) {
			case Constant.DRAWER_MAP_TYPES_ROADMAP:
				myGoogleMapService.changeMapType(GoogleMap.MAP_TYPE_NORMAL);
				currentMapType = GoogleMap.MAP_TYPE_NORMAL;
				break;
			case Constant.DRAWER_MAP_TYPES_SATELLITE:
				myGoogleMapService.changeMapType(GoogleMap.MAP_TYPE_SATELLITE);
				currentMapType = GoogleMap.MAP_TYPE_SATELLITE;
				break;
			case Constant.DRAWER_MAP_TYPES_HYBRID:
				myGoogleMapService.changeMapType(GoogleMap.MAP_TYPE_HYBRID);
				currentMapType = GoogleMap.MAP_TYPE_HYBRID;
				break;
			default:
				break;
			}

			// // Reset color for all child items.
			// for (int i = 0; i <
			// parent.getExpandableListAdapter().getChildrenCount(groupPosition);
			// i++) {
			// NavDrawerItem child = (NavDrawerItem)
			// parent.getExpandableListAdapter().getChild(groupPosition, i);
			// if (i != childPosition) {
			// child.setBackgroundColor(getResources().getColor(R.color.list_background));
			// } else {
			// child.setBackgroundColor(getResources().getColor(R.color.list_background_pressed));
			// }
			// }
			// parent.invalidateViews();
			int index = parent.getFlatListPosition(ExpandableListView.getPackedPositionForChild(groupPosition, childPosition));
			parent.setItemChecked(index, true);
			setTitle(tag.getTitle());
			mDrawerLayout.closeDrawer(parent);
			return false;
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// toggle nav drawer on selecting action bar app icon/title
		if (mDrawerToggle.onOptionsItemSelected(item)) {
			return true;
		}
		// Handle action bar actions click
		switch (item.getItemId()) {
		case R.id.action_settings:
			Intent settingsIntent = new Intent(this, SettingsActivity.class);
			startActivityForResult(settingsIntent, RESULT_SETTINGS);
			return true;
		case R.id.action_about:
			dialog = new Dialog(context);
			dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
			dialog.setContentView(R.layout.diag_input_friend_location);

			Button btnOK = (Button) dialog.findViewById(R.id.btnFriendLocationOK);
			btnOK.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {

					dialog.dismiss();
				}
			});

			dialog.show();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case RESULT_SETTINGS:
			// TODO
			break;

		}
	}

	/* *
	 * Called when invalidateOptionsMenu() is triggered
	 */
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// if nav drawer is opened, hide the action items
		boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerListView);
		menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
		menu.findItem(R.id.action_about).setVisible(!drawerOpen);
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public void setTitle(CharSequence title) {
		mTitle = getResources().getString(R.string.app_name) + " - " + title;
		getActionBar().setTitle(mTitle);
	}

	/**
	 * When using the ActionBarDrawerToggle, you must call it during
	 * onPostCreate() and onConfigurationChanged()...
	 */

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		// Sync the toggle state after onRestoreInstanceState has occurred.
		mDrawerToggle.syncState();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		// Pass any configuration change to the drawer toggls
		mDrawerToggle.onConfigurationChanged(newConfig);
	}
}
